package com.daxiang.core.pc.web;

import lombok.extern.slf4j.Slf4j;
import org.openqa.selenium.Capabilities;
import org.openqa.selenium.chrome.ChromeOptions;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * Created by jiangyitao.
 */
@Slf4j
public class ChromeDevice extends BrowserDevice {

    public ChromeDevice(Browser browser, BrowserServer browserServer) {
        super(browser, browserServer);
    }

    @Override
    protected Capabilities newCaps(Capabilities capsToMerge) {
        ChromeOptions chromeOptions = new ChromeOptions();
        chromeOptions.addArguments("--ignore-certificate-errors");
        chromeOptions.addArguments("no-default-browser-check");
        try {
            // chromedriver每次启动都会创建新的用户数据文件夹，所以每次打开都是新安装的状态
            // 指定用户数据文件目录，启动时读取缓存
            Path path = Paths.get(System.getProperty("user.dir"), "chrome-data", getDeviceId());
            String dir = Files.createDirectories(path).toString();
            log.info("ChromeDevice#newCaps user-data-dir=" + dir);
            chromeOptions.addArguments("--user-data-dir=" + dir);
        } catch (IOException e) {
            log.error("ChromeDevice#newCaps Failed! {}", e.getMessage());
            e.printStackTrace();
        }

        // **** 以上capabilities可被传入的caps覆盖 ****

        chromeOptions.merge(capsToMerge);

        // **** 以下capabilities具有更高优先级，将覆盖传入的caps ****

        if (!StringUtils.isEmpty(browser.getPath())) {
            chromeOptions.setBinary(browser.getPath());
        }

        return chromeOptions;
    }
}
